<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { ref, reactive } from "vue";
import { ElMessage } from 'element-plus';
import Inputter from "@/components/Inputter.vue";
import Password from "@/components/Password.vue";
import instance from '@/utils/request';
import { useUserStore } from "@/stores/user";
import router from "@/router/router";

/*
    已废弃
*/

// 用户个人中心页面
const user = useUserStore();

let user_name = ref("");
let user_password = ref("");

const dialogVisible = ref(false);

interface RuleForm {
  user_name: string
  user_password: string
  user_password_again: string
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  user_name: '',
  user_password: '',
  user_password_again: ''
});

// 确认密码验证
const password1 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空！'));
  }
  else {
    if (ruleForm.user_password_again !== '') {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField('user_password_again');
    }
    callback();
  }
}
const password2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('两次密码不一致！'));
  }
  else if (value !== ruleForm.user_password) {
    callback(new Error('两次密码不一致！'));
  }
  else {
    callback();
  }
}

const rules = reactive<FormRules<RuleForm>>({
  user_name: [
    { required: true, message: '账号名不能为空！', trigger: 'blur' },
    { min: 1, max: 8, message: '1-8个字符', trigger: 'blur'}
  ],
  user_password: [
    { required: true, message: '密码不能为空！', trigger: 'blur' },
    { validator: password1, trigger:'blur' }
  ],
  user_password_again: [
    { required: true, message: '两次密码不一致！', trigger: 'blur' },
    { validator: password2, trigger:'blur' }
  ]
});

const submitForm =  (formEl: FormInstance | undefined) => {
  // 提交表单
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) register();
  });
}

function open() {
  // 打开注册对话框
  dialogVisible.value = true;
}

function login() {
  // 登录
  if(user.user_id !== null) {
    router.push('/user/center/usermessage');
  }
  instance.request({
    url: 'user/center/login',
    method: 'POST',
    data: {
      user_name: user_name.value,
      user_password: user_password.value
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "登录失败！",
            type: "error"
          });
        }
        if(response.data.code === "ERROR_ACCOUNT") {
          ElMessage({
            message: "账号不存在！",
            type: "error"
          });
        }
        if(response.data.code === "ERROR_PASSWORD") {
          ElMessage({
            message: "账号或密码有误！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          user.login(response.data.data, user_name.value);
          router.push('/user/center/usermessage');
        }
      })
      .catch(function(error){
        console.log(error);
        ElMessage({
          message: "登录失败！",
          type: "error"
        });
      });
}

function close() {
  // 关闭对话框
  dialogVisible.value = false;
}

function register() {
  // 注册
  instance.request({
    url: 'user/center/register',
    method: 'POST',
    data: {
      user_name: ruleForm.user_name,
      user_password: ruleForm.user_password
    },
    headers: { "User-Id": user.user_id }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "注册失败！",
            type: "error"
          });
        }
        if(response.data.code === "ERROR_ACCOUNT") {
          ElMessage({
            message: "账号名已被注册！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          ElMessage({
            message: "注册成功！",
            type: "success"
          });
          dialogVisible.value = false;
        }
      })
      .catch(function(error){
        console.log(error);
        ElMessage({
          message: "注册失败！",
          type: "error"
        });
      });
}
</script>

<template>
  <el-dialog
      v-model="dialogVisible"
      :show-close="false"
      align-center
      width="25%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <el-form
        label-width="12vh"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
    >
      <el-form-item label="账号名：" prop="user_name">
        <inputter width="200" v-model="ruleForm.user_name"/>
      </el-form-item>

      <el-form-item label="密码：" prop="user_password">
        <password width="200" v-model="ruleForm.user_password"/>
      </el-form-item>

      <el-form-item label="确认密码：" prop="user_password_again">
        <password width="200" v-model="ruleForm.user_password_again"/>
      </el-form-item>

    <div class="cancel-confirm">
      <el-button color="#568fc1" plain @click="close">
        <span>取消</span>
      </el-button>
      <el-button color="#568fc1" class="button-color"
                 @click="submitForm(ruleFormRef)">
        <span>注册</span>
      </el-button>
    </div>
    </el-form>
  </el-dialog>

  <div class="login">
    <span class="input-text">账号名：</span>
    <inputter width="200" v-model="user_name"/><br><br>
    <span class="input-text">密码：</span>
    <password width="200" v-model="user_password"/><br>
    <el-link @click="open" class="link" :underline="false">注册</el-link><br>
    <el-button  color="#568fc1" class="button-width button-color" @click="login">
      <span>登录</span>
    </el-button>
  </div>
</template>

<style scoped>
.login {
  margin: 10vh;
  height: 50vh;
  /* border: 1px solid black; */
}
.input-text {
  display: inline-block;
  width: 10vh;
  text-align: right;
}
.button-width {
  margin-left: 5vh;
  width: 200px;
}
.button-color {
  --el-button-hover-bg-color: rgb(238, 244, 249) !important;
  --el-button-hover-text-color: #568fc1 !important;
  --el-button-text-color: white !important;
}
.link {
  padding-left: 30vh;
}
.cancel-confirm {
  padding-top: 1vh;
  text-align: center;
}
</style>